from django.template import RequestContext
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from accounts.forms import UserForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout



def index(request):
    if request.user.is_authenticated:
         user = request.user
    return render_to_response('accounts/index.html',{'user':user})

def register(request):
    if request.user.is_authenticated():
        user = request.user
        return render_to_response('accounts/index.html',{'user':user})

    context = RequestContext(request)

    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)

        if user_form.is_valid():
            user = user_form.save()

            user.set_password(user.password)
            user.save()

            registered = True

        else:
            print user_form.errors

    else:
        user_form = UserForm()

    return render_to_response('accounts/register.html',{'user_form': user_form, 'registered': registered},context)


def user_login(request):
    if request.user.is_authenticated():
        user = request.user
        return render_to_response('accounts/index.html',{'user':user})

    context = RequestContext(request)

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/accounts/')
            else:
                return HttpResponse("Your account is disabled.")
        else:
            print "Invalid login details: {0}, {1}".format(username, password)
            return HttpResponse("Invalid login details supplied.")
    else:
        return render_to_response('accounts/login.html', {}, context)


@login_required
def user_logout(request):
    logout(request)

    return HttpResponseRedirect('/accounts/')
